package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.app.mapper.AppGroupMapper;
import com.ruoyi.common.enums.GroupUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.app.domain.bo.AppGroupUserBo;
import com.ruoyi.app.domain.vo.AppGroupUserVo;
import com.ruoyi.app.domain.AppGroupUser;
import com.ruoyi.app.mapper.AppGroupUserMapper;
import com.ruoyi.app.service.IAppGroupUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * APP群组Service业务层处理
 *
 * @author heike
 * @date 2023-01-29
 */
@RequiredArgsConstructor
@Service
public class AppGroupUserServiceImpl implements IAppGroupUserService {

    private final AppGroupUserMapper baseMapper;
    private final AppGroupMapper appGroupMapper;

    /**
     * 查询APP群组
     */
    @Override
    public AppGroupUserVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public List<AppGroupUserVo> queryByGroupAndPlace(Long groupId, String place) {
        AppGroupUserBo groupUserBo = new AppGroupUserBo();
        groupUserBo.setPlace(place);
        groupUserBo.setGroupId(groupId);
        return queryList(groupUserBo);
    }

    @Override
    public AppGroupUserVo queryByGroupMaster(Long groupId) {
        LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getPlace, GroupUser.MASTER.getCode());
        return baseMapper.selectVoOne(wrapper);
    }

    @Override
    public AppGroupUserVo queryByGroupAndUserId(Long groupId, Long userId) {
        LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getUserId, userId);
        return baseMapper.selectVoOne(wrapper);
    }

    /**
     * 查询APP群组列表
     */
    @Override
    public TableDataInfo<AppGroupUserVo> queryPageList(AppGroupUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppGroupUser> lqw = buildQueryWrapper(bo);
        Page<AppGroupUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询APP群组列表
     */
    @Override
    public List<AppGroupUserVo> queryList(AppGroupUserBo bo) {
        LambdaQueryWrapper<AppGroupUser> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(AppGroupUser::getPlace);
        lqw.orderByAsc(AppGroupUser::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public AppGroupUserVo queryUser(Long groupId) {
        LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(AppGroupUser::getPlace, GroupUser.MASTER.getCode()).eq(AppGroupUser::getGroupId, groupId).orderByAsc(AppGroupUser::getPlace).orderByAsc(AppGroupUser::getCreateTime);
        return baseMapper.selectVoOne(wrapper);
    }

    @Override
    public List<AppGroupUserVo> queryList(Long groupId) {
        AppGroupUserBo groupUserBo = new AppGroupUserBo();
        groupUserBo.setGroupId(groupId);
        return queryList(groupUserBo);
    }

    private LambdaQueryWrapper<AppGroupUser> buildQueryWrapper(AppGroupUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppGroupUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGroupId() != null, AppGroupUser::getGroupId, bo.getGroupId());
        lqw.eq(bo.getUserId() != null, AppGroupUser::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getPlace()), AppGroupUser::getPlace, bo.getPlace());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppGroupUser::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增APP群组
     */
    @Override
    public Boolean insertByBo(AppGroupUserBo bo) {
        AppGroupUser add = BeanUtil.toBean(bo, AppGroupUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改APP群组
     */
    @Override
    public Boolean updateByBo(AppGroupUserBo bo) {
        AppGroupUser update = BeanUtil.toBean(bo, AppGroupUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改APP群组
     */
    @Override
    public Boolean updateByVo(AppGroupUserVo vo) {
        AppGroupUser update = BeanUtil.toBean(vo, AppGroupUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMaster(AppGroupUserVo vo, AppGroupUserVo master) {
        vo.setPlace(GroupUser.MASTER.getCode());
        master.setPlace(GroupUser.MEMBER.getCode());
        return updateByVo(vo) && updateByVo(master);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppGroupUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除APP群组
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int removeUser(Long groupId, Long userId, Integer sign, Long nextId) {
        if (sign.equals(2)) {
            //直接删除群
            return appGroupMapper.deleteById(groupId);
        } else {
            //如果退出的是群主，转让群主给其他用户
            if (sign.equals(1)) {
                LambdaUpdateWrapper<AppGroupUser> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getUserId, nextId).set(AppGroupUser::getPlace, GroupUser.MASTER);
                baseMapper.update(null, wrapper);
            }
            LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getUserId, userId);
            return baseMapper.delete(wrapper);
        }
    }

    @Override
    public int removeUser(Long groupId, Long userId) {
        LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getUserId, userId);
        return baseMapper.delete(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeUser(Long groupId, List<String> usernames) {
        usernames.forEach(e -> {
            if (StringUtils.isNotBlank(e)) {
                LambdaQueryWrapper<AppGroupUser> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(AppGroupUser::getGroupId, groupId).eq(AppGroupUser::getUserId, e);
                baseMapper.delete(wrapper);
            }
        });
        return true;
    }
}
